package controllers

import (
	"github.com/astaxie/beego"
	"sort"
	"crypto/sha1"
	"strings"
	"fmt"
	"log"
)

type WxController struct {
	beego.Controller
}

const token = "hellowx"

func (c *WxController) Get() {

	ok := authSignature(&c.Controller)
	if ok {
		c.Ctx.WriteString("hellowx")
	}
}

func authSignature(c *beego.Controller) bool {
	signature := c.GetString("signature")
	timestamp := c.GetString("timestamp")
	nonce := c.GetString("nonce")
	//echostr := c.GetString("echostr")

	if signature == makeSignature(timestamp, nonce) {
		log.Println("validate ok")
		return true
	} else {
		log.Println("validate error")
		return false
	}
}

func makeSignature(timestamp, nonce string) string {

	s := sha1.New()

	arr := []string{timestamp, nonce, token}
	sort.Strings(arr)

	s.Write([]byte(strings.Join(arr, "")))

	return fmt.Sprintf("%x", s.Sum(nil))
}
